package com.smile.weather2.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.smile.weather2.model.CityInfo;
import com.smile.weather2.model.CityInfo.CityInfoBean;
import com.smile.weather2.db.api.CityDaoApi;

import java.util.ArrayList;
import java.util.List;

/**
 * 城市信息数据库操作类
 * Created by smile on 2016/8/24.
 */
public class CityDao implements CityDaoApi {

    private DBHelper mHelper = null;

    public CityDao(Context context) {
        mHelper = new DBHelper(context);
    }

    @Override
    public void insertCity(CityInfoBean cityInfoBean) {
        SQLiteDatabase db = mHelper.getWritableDatabase();

        db.execSQL("insert into city(c_city, c_cnty, c_id, c_lat, c_lon, c_prov) values(?, ?, ?, ?, ?, ?)",
                new Object[]{cityInfoBean.getCity(), cityInfoBean.getCnty(), cityInfoBean.getId(), cityInfoBean
                        .getLat(), cityInfoBean.getLon(), cityInfoBean.getProv()});

        db.close();
    }

    @Override
    public CityInfo getCityInfo(String cityName) {

        SQLiteDatabase db = mHelper.getWritableDatabase();
        String current_sql_sel = "SELECT  *from city where c_city like '%" + cityName + "%'";
        Cursor cursor = db.rawQuery(current_sql_sel, null);

        CityInfo cityInfo = new CityInfo();
        List<CityInfoBean> city_info = new ArrayList<>();

        while (cursor.moveToNext()) {
            CityInfoBean cityInfoBean = new CityInfoBean();
            cityInfoBean.setCity(cursor.getString(cursor.getColumnIndex("c_city")));
            cityInfoBean.setCnty(cursor.getString(cursor.getColumnIndex("c_cnty")));
            cityInfoBean.setId(cursor.getString(cursor.getColumnIndex("c_id")));
            cityInfoBean.setLat(cursor.getString(cursor.getColumnIndex("c_lat")));
            cityInfoBean.setLon(cursor.getString(cursor.getColumnIndex("c_lon")));
            cityInfoBean.setProv(cursor.getString(cursor.getColumnIndex("c_prov")));

            city_info.add(cityInfoBean);
        }
        cityInfo.setCity_info(city_info);

        return cityInfo;
    }
}
